
var shareDomainUrl; //动态服务域名 

var Public = Public ? Public : {};
//域名配置
Public.domain = {
    'test': 'http://120.25.102.60:8186/',
    'pub': 'https://rmbap.renmainiu.cn/'
}
Public.appid = {
    'lktpt': 'wx297700027ab5110b',
    'bcd': 'wx9f08099ef1a3908e',
    'lktplus': 'wxd11fe6f954fe6257',
    'lkt': 'wx222333de160deec8'
}
Public.pahost = {
    'lktpt': 'liketuitestyingshe.baoxiandashi.cn',
    'bcd': 'liketuitest.baoxiandashi.cn',
    'lktplus': 'lktplusym_',
    'lkt': 'lklktmain.91lkt.cntzs'
}
Public.imgurl = {
    'lktpt': '/img/erwema_lktpt.png',
    'bcd': '/img/erwema_bcd.png',
    'lktplus': '/img/erwema_plus.png',
    'lkt': '/img/erwema_tui@2x.png'
}
Public.userInfo = {
    'uid': 'oTrHGt1xgNYvx1jYQdVllneqtp9E',
    'id': '10000231',
    'sid': '814218768b264a2fe07cfb3766198ae5'
}
function encodeUTF8(s) {
    var i, r = [], c, x;
    for (i = 0; i < s.length; i++)
        if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
        else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
        else {
            if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
                c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
                    r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
            else r.push(0xE0 + (c >> 12 & 0xF));
            r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
        };
    return r;
}

// 字符串加密成 hex 字符串
function sha1(s) {
    var data = new Uint8Array(encodeUTF8(s))
    var i, j, t;
    var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
    s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
    for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
    s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
    s[l - 1] = data.length << 3;
    var w = [], f = [
        function () { return m[1] & m[2] | ~m[1] & m[3]; },
        function () { return m[1] ^ m[2] ^ m[3]; },
        function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
        function () { return m[1] ^ m[2] ^ m[3]; }
    ], rol = function (n, c) { return n << c | n >>> (32 - c); },
        k = [1518500249, 1859775393, -1894007588, -899497514],
        m = [1732584193, -271733879, null, null, -1009589776];
    m[2] = ~m[0], m[3] = ~m[1];
    for (i = 0; i < s.length; i += 16) {
        var o = m.slice(0);
        for (j = 0; j < 80; j++)
            w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
                t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
                m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
        for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
    };
    t = new DataView(new Uint32Array(m).buffer);
    for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);

    var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
        return (e < 16 ? "0" : "") + e.toString(16);
    }).join("");
    return hex;
}
Public.ajaxLoadData = function (isshowloading, url, data, type, contentType, callback, errorCB, async) {
    async = typeof (async) != "undefined" ? async : true;
    contentType = (contentType == "json" || contentType == "JSON") ? "application/json" : "application/x-www-form-urlencoded";
    if (isshowloading) { //显示数据loading时弹窗
        showLoadingWrap(1, 1);
    }
    if (type == "POST" || type == "post") {
        url = url + "?r=" + parseInt(Math.random() * 100, 10);
        data = JSON.stringify(data);
    } else {
        url = url + "&r=" + parseInt(Math.random() * 100, 10);
    }
    let _appKey = window.sessionStorage.getItem("appKey");
    let _jmsz = window.sessionStorage.getItem("jmsz"); 
    let timestamp = parseInt(new Date().getTime() / 1000);
    const authAppSecret = "53d094ee4f65d30863285dba3b449f7b";
    let checkSum = sha1(authAppSecret + _jmsz + "tp" + timestamp + timestamp);
    
    let ua = window.navigator.userAgent;
    let mobileType = (ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1) ? 1 : 0;
    let ua_version = ua.toLowerCase().split("networking gang/")[1];
    let appVersion;
    let wind_storage = window.localStorage;
    let _uniqueId =  wind_storage.uniqueId;
    let _wapHeader;
    if (mobileType) {
        appVersion = ua_version ? ua_version : "1.0.0";
        wapHeader = JSON.stringify({ "mobileType": mobileType, "appVersion": appVersion });
    } else {
        if (ua_version) {
            let ua_info = ua_version.split("/");
            appVersion = ua_info[0] ? ua_info[0] : "1.0.0";
            let channelId = ua_info[1] ? ua_info[1] : 1;
            wapHeader= JSON.stringify({ "mobileType": mobileType, "appVersion": appVersion, "channelId": channelId });
        }
    }
    let _header = {};
    if(url.indexOf("getWapConfig")  === -1){
        _header =  {
            'Content-Type': contentType, 
            uniqueId: _uniqueId,
            'appKey': _appKey,
            'nonce':  "tp" + timestamp,
            'curTime':  timestamp,
            'checkSum':  checkSum,
            "wapHeader": _wapHeader,
        }
    }else{
        _header=  {
            'Content-Type': contentType, 
            uniqueId: _uniqueId,
            "wapHeader": _wapHeader,
        }
    }
    $.ajax({
        url: url,
        data: data,
        type: type,
        headers: _header,
        timeout: 8000,
        success: function (jsonData) {
            showLoadingWrap(0, 0);
            var headData = jsonData.head;
            if (callback != null) {
                var protocol = window.location.protocol;
                var host = window.location.host;
                var getNewurl = window.location.href;
                if (headData.code == '110' || headData.code == 110) {
                    // 判断是否是微信浏览器
                    if (isWeiXinBrowser()) {
                        if (getNewurl.indexOf("&pmsg=") > -1) {
                            getNewurl = getNewurl.split("&pmsg=")[0];
                        }
                        window.localStorage.removeItem('wxUnionId');
                    } else {
                        // 判断是否是正式服
                        if (host.indexOf("com") > -1 || host.indexOf("com") > -1) {
                            location.href = protocol + "//" + host + "/wxerror.html";
                            return false;
                        } else {
                            window.localStorage.wxUnionId = Public.userInfo.uid;
                            window.localStorage.userSessionId = Public.userInfo.sid;
                        }
                    }
                    if (getNewurl.indexOf("?") > -1) {
                        getNewurl = getNewurl + "&v=" + parseInt(Math.random() * 100, 10);
                    } else {
                        getNewurl = getNewurl + "?v=" + parseInt(Math.random() * 100, 10);
                    }
                    window.location.replace(getNewurl);
                } else if (url.indexOf("rticleDetail") > -1 && (headData.code === 103 || headData.code === 500)) {
                    //文章找不到返回码103 、500 需跳转到文章审核页面    
                    window.localStorage.isFirstIn = 0;
                    window.location.replace(protocol + "//" + host + "/pages/404/noFoundArticle.html?articleId=1&v=" + parseInt(Math.random() * 100, 10));
                } else if (headData.code != 200) {
                    if (errorCB != null) {
                        errorCB(jsonData)
                    } else if (url.indexOf("searchBrandInfo") <= -1) {
                        showTit(headData.msg, "no", function () {
                            // window.location.href =protocol+"//"+ host + "/pages/404/404.html"
                            return;
                        });
                    }
                } else {
                    // 执行 回调操作
                    callback(jsonData);
                }
            }
        },
        async: async,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // 注意：如果发生了错误，错误信息（第二个参数） 是"timeout", "error", "notmodified" 和 "parsererror" ,"null"。
            showLoadingWrap(0, 0);
            if (textStatus == 'timeout') {
                showTit("网络连接超时,请稍后再试！", "warn");
                return false;
            }
            var msg = "连接服务器失败";
            if (errorCB) {
                showTit(msg, "no", function () { return; });
            }
        }
    });
};
// 获取接口访问域名
function getAdminPath() {
    var hostname = window.location.hostname;
    if (hostname.indexOf('192.168.') > -1 || hostname.indexOf('localhost') > -1 || hostname.indexOf('127.0.0.1') > -1) {
        return Public.domain.test;
    }
    return Public.domain.pub;
}
// 获取公众号appid
function getPAAppidByHost() {
    var hostname = window.location.hostname;
    if (hostname.indexOf(Public.pahost.lktpt) > -1) {
        return Public.appid.lktpt;
    }
    if (hostname.indexOf(Public.pahost.bcd) > -1) {
        return Public.appid.bcd;
    }
    if (hostname.indexOf(Public.pahost.lkt) > -1) {
        return Public.appid.lkt;
    }
    return Public.appid.lkt;
}

// 获取公众号QRC
function getPAQrcByHost() {
    var hostname = window.location.hostname;
    if (hostname.indexOf(Public.pahost.lktpt) > -1) {
        return Public.imgurl.lktpt;
    }
    if (hostname.indexOf(Public.pahost.bcd) > -1) {
        return Public.imgurl.bcd;
    }
    if (hostname.indexOf('lktzs') > -1) {
        return Public.imgurl.lkt;
    }
    return Public.imgurl.lkt;
}

var globalVar = {};
$(window).on("orientationchange", function (event) {
    if (window.orientation == 0) {
        View.scaleView();
    }
});
var View = {
    scaleView: function () {
        width = $(window).width();
        scale = width / parseFloat(640 * 2);
        console.log()
        viewPort = '<meta name="viewport" content="width=640, initial-scale=' + scale + ',minimum-scale=' + scale + ',maximum-scale=' + scale + '" />';
        $('head').append(viewPort);
    }
};
// 停止冒泡
function stopBubble(e) {
    if (e.stopPropagation) {
        // this code is for Mozilla and Opera
        e.stopPropagation();
    } else if (window.event) {
        // this code is for IE
        window.event.cancelBubble = true;
    }
    return false;
}
// 表单序列化成对象
jQuery.prototype.serializeObject = function () {
    var obj = {};
    $.each(this.serializeArray(), function (index, param) {
        if (!(param.name in obj)) {
            obj[param.name] = param.value;
        }
    });
    return obj;
};
/**
 * 获取url 参数值
 */
function getCNParam() {
    var url = window.location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            //就是这句的问题
            theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
            //之前用了unescape()
            //才会出现乱码
        }
    }
    return theRequest;
}
//获取根目录路径
function rootPath() {
    var path = "";
    //获取当前网址
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录
    var pathName = window.document.location.pathname;
    if (pathName == "/" || pathName == "") {
        path = curWwwPath;
        if (curWwwPath.indexOf("?") > 0) {
            path = curWwwPath.split("?")[0];
        }
    } else {
        var pos = curWwwPath.indexOf(pathName);
        //获取主机地址，
        var localhostPaht = curWwwPath.substring(0, pos);
        //获取带"/"的项目名
        path = localhostPaht;
    }

    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    if (curWwwPath.indexOf(".com") > 0) {
        if (curWwwPath.split("?")[0].indexOf(".com") > 0) {

        } else {
            path = path + projectName
        }
    } else {
        path = path + projectName
    }
    var str = path.substr(path.length - 1, 1)
    if (str == '/') {
        path = path.substr(0, path.length - 1);
    }
    return path;
};

//x消息提醒
var showTit = (function ($, w) {
    return function (msg, flag, foo, close) {
        $("#shadeBGDiv").css({ "z-index": "99999992" }); //用户登陆错误提示 需覆盖登陆弹窗
        var _ico = "success-tips-icon";//成功(success-tips-icon)，失败(fail-tips-icon)，提醒(warn-tips-icon)对应不同的class
        var _text = "成功";
        if (flag == "no") {
            _ico = "fail-tips-icon";//no的样式
            _text = "失败";
        } else if (flag == "warn") {
            _ico = "warn-tips-icon";//no的样式
            _text = "提醒";
        }
        if ($("#shadeBGDiv").length <= 0) {
            $("body").append("<div id=\"shadeBGDiv\" class=\"shadeDiv\"></div>");
        }
        $("#successInfor").remove();
        var str = '';
        str += '<div class="public_result_div ' + _ico + '" id="successInfor">';
        // str +='<p class="tipsName">' + _text + '</p>';
        str += '<span class="success_result">' + msg + '</span>';
        str += '</div>';
        $("body").append(str);
        //计算背景宽
        var _h1 = $(window).height();
        var _h2 = w.document.body.offsetHeight;
        var _h = "";
        if (_h1 > _h2) {
            _h = _h1 + "px";
        } else {
            _h = _h2 + "px";
        }
        w.document.getElementById("shadeBGDiv").style.height = _h;
        $("#shadeBGDiv").css({ "opacity": "0.1" }).fadeIn("fast");
        $("#successInfor").fadeIn("fast");
        w.titHide = function () {
            $("#successInfor").fadeOut();
            if (close == 1) {
                $("#shadeBGDiv").css({ "z-index": "4900000" });
            } else {
                $("#shadeBGDiv").fadeOut("fast");
            }
            if (foo) {
                foo();
            }
        };
        setTimeout("titHide()", 1500);
    };
})(jQuery, window);

// 提示信息确认
var showConfirm = (function ($, w) {
    return function (className, tipsTitle, tipsContent, toSetName, hasCancel, funCB, tapBg) {
        if ($("body").find("." + className).length > 0) {
            $("." + className).show();
            return false;
        }
        var cancelHtml = "", tapBgHtml = "";
        if (hasCancel) {
            cancelHtml = '<div class="setbox-footer-item setbox-footer-left flex-1" onclick="tap2HideTips()">取消</div>';
        }
        if (!checkStringIsNull(tapBg) && !tapBg) {
            tapBgHtml = "";
        } else {
            onclick = 'onclick="tap2HideTips()"';
        }
        var strHtml = '<div class="settingtips ' + className + '"  ' + tapBgHtml + '>' +
            '<div class="settingtips-box"  onclick="returnNull(event)"> ' +
            '<div class="title">' + tipsTitle + '</div>' +
            '<div class="tips" >' + tipsContent + '</div>' +
            '<div class="setbox-footer flex">' +
            cancelHtml +
            '<div class="setbox-footer-item setbox-footer-right flex-1" onclick="' + funCB + '()">' + toSetName + '</div>' +
            '</div></div></div>'
        $("body").append(strHtml);
        $("." + className).show();
        var boxHeight = $("." + className + " .settingtips-box").height();
        var windowHeight = $(window).height();
        $("." + className + " .settingtips-box").css("top", ((windowHeight - boxHeight) / 2) + "px");

    };
})(jQuery, window);
//loading 加载框加载中。。
//x消息提醒
var showLoadingWrap = (function ($, w) {
    return function (isAdd, isShow) {
        //isAdd :添加节点到dom中； isShow：显示loadingWrap
        if (isAdd) {
            var str = '';
            str += '<div class="loadingWrap" onclick="returnNull()">';
            str += '<div class="loadingGif" style=""></div>';
            // str +='<p class="loadingFont">数据加载中...</p>';
            str += '</div>';
            $("body").append(str);
            //计算背景宽
            var _h1 = $(window).height();
            var _h2 = w.document.body.offsetHeight;
            var _h = "";
            if (_h1 > _h2) {
                _h = _h1 + "px";
            } else {
                _h = _h2 + "px";
            }
            $(".loadingWrap").css({ "z-index": "999999" });
        }
        if (isShow) {
            $(".loadingWrap").show();
        } else {
            $(".loadingWrap").hide();
            $(".loadingWrap").remove();
        }
    };
})(jQuery, window);

/*判断是否在微信浏览器上打开*/
function isWeiXinBrowser() {
    var ua = window.navigator.userAgent.toLowerCase();
    //console.log(ua);mozilla/5.0 (iphone; cpu iphone os 9_1 like mac os x) applewebkit/601.1.46 (khtml, like gecko)version/9.0 mobile/13b143 safari/601.1
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
    return false;
}
/**
 * 是否爲空
 * @param {Object} str
 */
function checkStringIsNull(str) {
    str = $.trim(str);
    if (str != null && str != "null" && str != '' && str != "" && str != " " && str != undefined && str != "undefined") {
        return false;
    } else {
        return true;
    }

}
function isAndroind() {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    return isAndroid;
}
function isIos() {
    var u = navigator.userAgent;
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    return isiOS;
}

//点击反空 清楚默认事件，点击穿透
function returnNull(event) {
    event.stopPropagation();
    event.preventDefault();
    return false;
}
//tap 隐藏setting提示弹框
function tap2HideTips() {
    returnBodyHeight(); // 恢复body高度 
    $(".settingtips").hide();
    return false;
}
//页面跳转
function toHref(pageHerf, ownParmas) {
    if (ownParmas) {
        window.location.href = pageHerf + "&v=" + parseInt(Math.random() * 100, 10);
    } else {
        window.location.href = pageHerf + "?v=" + parseInt(Math.random() * 100, 10);
    }
}
let isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1;
let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

//这是必须要写的，用来创建一些设置
function setupWebViewJavascriptBridge(callback) {
    //Android使用
    if (isAndroid) {
        if (window.WebViewJavascriptBridge) {
            callback(window.WebViewJavascriptBridge)
        } else {
            document.addEventListener(
                'WebViewJavascriptBridgeReady',
                function () {
                    callback(window.WebViewJavascriptBridge)
                },
                false
            );
        }
        console.log('tag', 'android')
        sessionStorage.phoneType = 'android'
    }

    //iOS使用
    if (isiOS) {
        if (window.WebViewJavascriptBridge) {
            return callback(window.WebViewJavascriptBridge);
        }
        if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
        }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function () {
            document.documentElement.removeChild(WVJBIframe)
        }, 0);
        console.log('tag', 'ios');
        sessionStorage.phoneType = 'ios'
    }
}
//注册回调函数，第一次连接时调用 初始化函数(android需要初始化,ios不用)
setupWebViewJavascriptBridge(function (bridge) {
    if (isAndroid) {
        //初始化
        bridge.init(function (message, responseCallback) {
            var data = {
                'Javascript Responds': 'Wee!'
            };
            responseCallback(data);
        })
    }
})
// 微信api 初始化  
function generateJsConfig(imgPosition, articleOprateIndex) {
    let parmas = {
        maxCount: 1,  //选择相册的最大数，若是相机拍照则只能为1
        sourceType: ['album', 'camera'], //相册&&拍照，可选其一 
        method: "articleContentImg"
    };
    setupWebViewJavascriptBridge(function (bridge) {
        bridge.callHandler("chooseImages", parmas, (res) => {
            let imagesArr = res.split("@X@");
            // imgPosition, articleOprateIndex：分别是文章插入图片的正文位置 、 操作数
            showLoadingWrap(1, 1);
            uploadUserArticleImg(imagesArr[0], imgPosition, articleOprateIndex);//编辑文章插入图片，无需保存
            setTimeout(() => {
                showLoadingWrap(0, 0);
            }, 800);
        })
    })


}

function setQRCPhone() {
    returnBodyHeight(); // 恢复body高度 
    var protocol = window.location.protocol;
    var host = window.location.host;
    toHref(protocol + "//" + host + "/pages/setting/setup.html");
}
//微信 上传至后台  编辑文章插入的图片
function uploadUserArticleImg(articleImgUrl, imgPosition, articleOprateIndex) {
    console.log(articleImgUrl);
    console.log(imgPosition, articleOprateIndex);
    if (imgPosition == "pre") {
        $("#editBox").prev().show();
        $(".edit-context").prepend("<div class='opration" + articleOprateIndex + "' style='width:100%;' ><img src='" + articleImgUrl + "' style='width:100%;'></img></div>");
    } else if (imgPosition == "after") {
        $("#editBox").prev().show();
        // var articleVersionNum = window.localStorage.articleVersionNum; //判断是否为老文章==1，新文章==2
        // if (articleVersionNum == 1) {
        //     var strHtml = ""
        //     strHtml += "<div class='contentitem opration" + articleOprateIndex + "' data-type='2' data-contxt='" + articleImgUrl + "' style='width:100%;' >" +
        //         "<img src='" + articleImgUrl + "' style='width:100%;'></img></div>"
        //     $("#editBox").prev().after(strHtml)
        // } else {
        $("#editBox").prev().after("<div class='opration" + articleOprateIndex + "' style='width:100%;' ><img src='" + articleImgUrl + "' style='width:100%;'></img></div>")
        // }
    }
    $(".edit-box").remove();
}
// textarea \n 转为 <br/>
function textEnter2Br(textVal) {
    return (textVal.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' '));
}
// html 2 textarea   <br/> 转为 \n
function textBr2Enter(textHtml) {
    return (textHtml.replace(/\<br\/\>/g, '\n').replace(/\<br\>/g, '\n'));
}
// 删除   <br/> &&  \n
function delTextBrEnter(textHtml) {
    return (textHtml.replace(/\<br\/\>/g, ' ').replace(/\<br\>/g, ' ').replace(/\r\n/g, ' ').replace(/\n/g, ' ').replace(/\s/g, ' '));
}
// 弹窗时 将body.height 截取到窗口大小
function splitBodyHeight() {
    $("body").css({
        "height": $(window).height() + "px",
        "overflow": "hidden",
        "position": "fixed",
        "left": "0",
        "top": "0",
    });
}
// 弹窗消失时，恢复body.height 
function returnBodyHeight() {
    $("body").css({
        "height": "auto",
        "overflow": "auto",
        "position": "relative",
    });
}